package net.bblot.lottery.util;

import android.text.TextUtils;

import net.bblot.lottery.activity.QApplication;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by feng on 2017/9/8.
 */

public class FileUtil {
    private static final String TAG = "FileUtil";
    public static boolean checkFileExit(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        boolean exit = file.exists();
        file = null;
        return exit;
    }

    public static boolean checkAssetsFileExit(String fileName) {
        InputStream in = null;
        try {
            in = QApplication.context.getAssets().open(fileName);
            Logger.e(TAG, "assets文件存在");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(in);
        }
        Logger.e(TAG, "assets文件不存在");
        return false;
    }

    public static boolean createFile(File file) {
        if (file != null) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void deleteAllFile(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteAllFile(f);
            }
            file.delete();
        }
    }

    public static List<File> searchFile(String fileDir, String fileName) {
        if (TextUtils.isEmpty(fileDir) || TextUtils.isEmpty(fileName)) {
            return null;
        }
        File file = new File(fileDir);
        if (file.isFile()) {
            return null;
        }
        List<File> fileList = new ArrayList<>();
        searchFile(fileList, file, fileName);
        return fileList;
    }

    public static void searchFile(List<File> fileList, File file, String fileName) {
        File[] files = file.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isFile()) {
                if (f.getName().equals(fileName)) {
                    fileList.add(f);
                }
            } else {
                searchFile(fileList, f, fileName);
            }
        }
    }
}
